package com.damai.utils.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.citywithincity.utils.IoUtil;

public class CpuMemSnapshot {
	private Process proc;
	private BufferedReader br;
	
	public CpuMemSnapshot(){
		
	}
	
	
	public void startup() throws IOException{
		proc = Runtime.getRuntime().exec("top");
		br = new BufferedReader(new InputStreamReader(proc
				.getInputStream()));
	}
	
	
	public String takeSnapshot() throws IOException{
		String info = br.readLine();
		StringBuilder s = new StringBuilder(info);
		s.append("\n");
		int index = 0;
		while (info != null) {
			info = br.readLine();
			++index;
			if(info.contains("kernel_task")){
				break;
			}
			if(index<=30){
				s.append(info);
				s.append("\n");
			}
		}
		return s.toString();
	}
	
	
	public void close(){
		if(proc!=null){
			proc.destroy();
			proc = null;
		}
		if(br!=null){
			IoUtil.close(br);
			br = null;
		}
		
	}
	
}
